package com.ruoyi.loan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.loan.dto.BeliefRecordDto;
import com.ruoyi.loan.entity.BeliefRecord;
import com.ruoyi.loan.entity.LoanRecord;
import com.ruoyi.loan.mapper.BeliefRecordMapper;
import com.ruoyi.loan.mapper.LoanRecordMapper;
import com.ruoyi.loan.service.BeliefRecordService;
import com.ruoyi.loan.vo.BeliefRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.zip.DataFormatException;

/**
 * @Author lin
 * @Date 2022/4/5 0:21
 */
@Service
public class BeliefRecordServiceImpl extends ServiceImpl<BeliefRecordMapper, BeliefRecord> implements BeliefRecordService {

    @Resource
    private BeliefRecordMapper beliefRecordMapper;

    @Autowired
    private LoanRecordMapper loanRecordMapper;

    /**
     * 添加失信学生列表
     *
     * @param beliefRecord 信息
     * @return
     */
    @Override
    public void saveBelief(BeliefRecord beliefRecord) {
        //当前时间搓
        long currentTimeMillis = System.currentTimeMillis();
        beliefRecord.setCreateTime(new Timestamp(currentTimeMillis));
        LoanRecord loanRecord = loanRecordMapper.selectById(beliefRecord.getLoanId());
        if (loanRecord == null) {
            throw new RuntimeException("不存在的贷款记录");
        }
        beliefRecord.setUserId(loanRecord.getUserId());
        baseMapper.insert(beliefRecord);
    }

    /**
     * 获取失信列表
     *
     * @param dto 参数
     * @return
     */
    @Override
    public PageInfo selectBeliefRecordList(BeliefRecordDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getSize());
        List<BeliefRecordVo> beliefRecordVos = beliefRecordMapper.selectBeliefRecordList(dto);
        for (BeliefRecordVo beliefRecordVo : beliefRecordVos) {
            Date adminTime = beliefRecordVo.getAdminTime();
            Date now = new Date();
            int adminTimeYear = adminTime == null ? now.getYear() : adminTime.getYear();
            int year = now.getYear() - adminTimeYear;
            int adminTimeMonth = adminTime == null ? now.getMonth() : adminTime.getMonth();
            int month = now.getMonth() - adminTimeMonth;
            Integer loanYears = beliefRecordVo.getLoanYears();
            int overtime = year * 12 + month - loanYears * 12;
            String overtimeStr = overtime < 0 ? "未逾期" : String.format("已逾期%d个月", overtime);
            beliefRecordVo.setOvertime(overtimeStr);
        }
        return new PageInfo(beliefRecordVos);
    }
}
